// 实现函数柯里化
const _ = require('lodash')

function sum(a, b, c) {
    return a + b + c
}

// const curried = _.curry(sum)

// console.log(curried(1,2,3))
// console.log(curried(1,2)(3))
// console.log(curried(1)(2,3))

// const curry = (fn) => {
//     return curriedFn = (...args) => {
//         if (args.length < fn.length) {
//             return (...rest) => curriedFn(...args.concat(rest))
//         }
//         return fn(...args)
//     }
// }

function curry(fn) {
    return function curriedFn() {
        const args = arguments
        if (args.length < fn.length) {
            return function() {
                return curriedFn(...Array.from(arguments).concat(Array.from(args)))
            }
        }
        return fn(...args)
    }
}

// 优化
// const curry = fn => curriedFn = (...args) => args.length < fn.length ? (...rest) => curriedFn(...args.concat(rest)) : fn(...args)


// const curry = (fn, arr = []) => (...args) => (
//     arg => arg.length === fn.length
//       ? fn(...arg)
//       : curry(fn, arg)
//   )([...arr, ...args])

const curried = curry(sum)

console.log(curried(1,2,3))
console.log(curried(1)(2,3))
console.log(curried(1,2)(3))
console.log(curried(1)(2)(3))
